package start.spring.basic.util.common;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;


/**
 * ****************************************************************************
 * http\https请求类
 *
 * @author(作者)：xuyongyun	
 * @author(复审人)：	Administrator 2018-5-23
 * @version(版本)1.0
 * @since 1.0
 ******************************************************************************
 */

public class HttpUtil {
	
	private final static String HTTPS = "https";
	private final static String HTTP = "http";
	
	public final static String GET = "GET";
	
	public final static String POST = "POST";
	
	/**
	 * 发送http/https请求
	 * 
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（GET、POST）
	 * @param requestParams 提交的数据
	 * @param contentType 请求内容类型
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 * @throws NoSuchProviderException 
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyManagementException 
	 * @throws IOException
	 */
	public static String request(String requestUrl,String requestMethod, String requestParams, String contentType)
		{
		String result = null;
		try {
			if(requestUrl!=null){
				//https请求
				if(requestUrl.indexOf(HttpUtil.HTTPS)==0){
					// 创建SSLContext对象，并使用我们指定的信任管理器初始化
					TrustManager[] tm = { new MyX509TrustManager() };
					SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
					sslContext.init(null, tm, new java.security.SecureRandom());
					// 从上述SSLContext对象中得到SSLSocketFactory对象
					SSLSocketFactory ssf = sslContext.getSocketFactory();

					URL url = new URL(requestUrl);
					HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
					conn.setSSLSocketFactory(ssf);
					
					conn.setDoOutput(true);
					conn.setDoInput(true);
					conn.setUseCaches(false);
					conn.setRequestMethod(requestMethod);
					//设置请求内容类型
					if(null != contentType){
						conn.setRequestProperty("Content-Type",contentType);
					}

					// 当outputStr不为null时向输出流写数据
					if(null != requestParams) {
						OutputStream outputStream = conn.getOutputStream();
						// 注意编码格式
						outputStream.write(requestParams.getBytes("UTF-8"));
						outputStream.close();
					}

					// 从输入流读取返回内容
					InputStream inputStream = conn.getInputStream();
					InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
					BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
					String str = null;
					StringBuffer buffer = new StringBuffer();
					while ((str = bufferedReader.readLine()) != null) {
						buffer.append(str);
					}

					// 释放资源
					bufferedReader.close();
					inputStreamReader.close();
					inputStream.close();
					inputStream = null;
					conn.disconnect();
					
					result = buffer.toString();
				}else if(requestUrl.indexOf(HttpUtil.HTTP)==0){
					URL httpurl = new URL(requestUrl);
					HttpURLConnection httpurlconnection = (HttpURLConnection) httpurl.openConnection();
					
					httpurlconnection.setDoOutput(true);
					httpurlconnection.setDoInput(true);
					httpurlconnection.setUseCaches(false);
					httpurlconnection.setRequestMethod(requestMethod);
					//设置请求内容类型
					if(null != contentType){
						httpurlconnection.setRequestProperty("Content-Type",contentType);
					}
					
					// 当outputStr不为null时向输出流写数据
					if (null != requestParams) {
						OutputStream outputStream = httpurlconnection.getOutputStream();
						// 注意编码格式
						outputStream.write(requestParams.getBytes("UTF-8"));
						outputStream.close();
					}
					
				    InputStream inStream = httpurlconnection.getInputStream();
				    InputStreamReader inputStreamReader = new InputStreamReader(inStream, "utf-8");
			        BufferedReader in = new BufferedReader(inputStreamReader);  
			        StringBuffer buffer = new StringBuffer();  
			        String line = "";  
			        while((line = in.readLine())!=null){  
			        	buffer.append(line);
			        }
			       
			        // 释放资源
			        in.close();
			        inputStreamReader.close();
				    inStream.close();
				    inStream = null;
				    httpurlconnection.disconnect();
					
				    result = buffer.toString();
				}
			}
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 发送http/https请求，调用方自己处理请求异常
	 * 
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（GET、POST）
	 * @param requestParams 提交的数据
	 * @param contentType 请求内容类型
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 * @throws Exception 
	 * @throws NoSuchProviderException 
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyManagementException 
	 * @throws IOException
	 */
	public static String requestUrl(String requestUrl,String requestMethod, 
			String requestParams, String contentType) throws Exception {
		String result = null;
		try {
			if(requestUrl!=null){
				//https请求
				if(requestUrl.indexOf(HttpUtil.HTTPS)==0){
					// 创建SSLContext对象，并使用我们指定的信任管理器初始化
					TrustManager[] tm = { new MyX509TrustManager() };
					SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
					sslContext.init(null, tm, new java.security.SecureRandom());
					// 从上述SSLContext对象中得到SSLSocketFactory对象
					SSLSocketFactory ssf = sslContext.getSocketFactory();

					URL url = new URL(requestUrl);
					HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
					conn.setSSLSocketFactory(ssf);
					
					conn.setDoOutput(true);
					conn.setDoInput(true);
					conn.setUseCaches(false);
					conn.setRequestMethod(requestMethod);
					//设置请求内容类型
					if(null != contentType){
						conn.setRequestProperty("Content-Type",contentType);
					}

					// 当outputStr不为null时向输出流写数据
					if(null != requestParams) {
						OutputStream outputStream = conn.getOutputStream();
						// 注意编码格式
						outputStream.write(requestParams.getBytes("UTF-8"));
						outputStream.close();
					}

					// 从输入流读取返回内容
					InputStream inputStream = conn.getInputStream();
					InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
					BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
					String str = null;
					StringBuffer buffer = new StringBuffer();
					while ((str = bufferedReader.readLine()) != null) {
						buffer.append(str);
					}

					// 释放资源
					bufferedReader.close();
					inputStreamReader.close();
					inputStream.close();
					inputStream = null;
					conn.disconnect();
					
					result = buffer.toString();
				}else if(requestUrl.indexOf(HttpUtil.HTTP)==0){
					URL httpurl = new URL(requestUrl);
					HttpURLConnection httpurlconnection = (HttpURLConnection) httpurl.openConnection();
					
					httpurlconnection.setDoOutput(true);
					httpurlconnection.setDoInput(true);
					httpurlconnection.setUseCaches(false);
					httpurlconnection.setRequestMethod(requestMethod);
					//设置请求内容类型
					if(null != contentType){
						httpurlconnection.setRequestProperty("Content-Type",contentType);
					}
					
					// 当outputStr不为null时向输出流写数据
					if (null != requestParams) {
						OutputStream outputStream = httpurlconnection.getOutputStream();
						// 注意编码格式
						outputStream.write(requestParams.getBytes("UTF-8"));
						outputStream.close();
					}
					
				    InputStream inStream = httpurlconnection.getInputStream();
				    InputStreamReader inputStreamReader = new InputStreamReader(inStream, "utf-8");
			        BufferedReader in = new BufferedReader(inputStreamReader);  
			        StringBuffer buffer = new StringBuffer();  
			        String line = "";  
			        while((line = in.readLine())!=null){  
			        	buffer.append(line);
			        }
			       
			        // 释放资源
			        in.close();
			        inputStreamReader.close();
				    inStream.close();
				    inStream = null;
				    httpurlconnection.disconnect();
					
				    result = buffer.toString();
				}
			}
		} catch(Exception ex) {
			throw ex;
		}
		return result;
	}
	
	/**
	 * 发送http/https请求
	 * 
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（GET、POST）
	 * @param timeOut 超时时间
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 * @throws NoSuchProviderException 
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyManagementException 
	 * @throws IOException
	 */
	public static String requestWsdl(String requestUrl,String requestMethod, int timeOut) throws Exception {
		
		String result = null;
			
		URL httpurl = new URL(requestUrl);
		HttpURLConnection httpurlconnection = (HttpURLConnection) httpurl.openConnection();
		
		if(timeOut>0) {
			httpurlconnection.setConnectTimeout(timeOut);
			httpurlconnection.setReadTimeout(timeOut);
		}
		
		httpurlconnection.setDoOutput(true);
		httpurlconnection.setDoInput(true);
		httpurlconnection.setUseCaches(false);
		httpurlconnection.setRequestMethod(requestMethod);
		
		
	    InputStream inStream = httpurlconnection.getInputStream();
	    InputStreamReader inputStreamReader = new InputStreamReader(inStream, "utf-8");
        BufferedReader in = new BufferedReader(inputStreamReader);  
        StringBuffer buffer = new StringBuffer();  
        String line = "";  
        while((line = in.readLine())!=null){  
        	buffer.append(line);
        }
       
        // 释放资源
        in.close();
        inputStreamReader.close();
	    inStream.close();
	    inStream = null;
	    httpurlconnection.disconnect();
		
	    result = buffer.toString();
		
		return result;
	}
	
	/**
	 * 获取POST请求发送的参数
	 * 
	 * 此方法获取post body中提交的内容，body中提交的内容仅能读取一次
	 * 
	 * @param request
	 * @return
	 */
	public static String getPostPrams(HttpServletRequest request) {
		StringBuffer sb = new StringBuffer();
		try {
			BufferedReader reader = request.getReader();
			char[] buf = new char[1024];
			int len = 0;
			while ((len = reader.read(buf)) != -1) {
				sb.append(buf, 0, len);
			}
			reader.close();
			reader = null;
		} catch (IOException e1) {
			e1.printStackTrace();
			return "";
		}
		return sb.toString();
	}
}
